package com.wang.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wang.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Classname PaymentController
 * @Description TODO
 * @Date 2024/10/15 13:56
 * @Created by pc
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        String result = paymentService.paymentInfo_OK(id);
        log.info("********result:" + result);
        return result;
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            // 设置自身超时调用时间的峰值为3秒，峰值内可以正常运行，超过了需要有兜底的方法处理，服务降级fallback
            // 这个方法最多容忍三秒钟 如果超过3秒自动执行服务降级方法 paymentInfo_TimeOutHandler
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_Timeout(@PathVariable("id") Integer id){
        // String result = paymentService.paymentInfo_Timeout(id);
        // log.info("********result:" + result);
      // return result;
        int timeNumber = 5;
        int i = 1/0;

        // try {
        //     TimeUnit.SECONDS.sleep(timeNumber);
        // } catch (InterruptedException e) {
        //     throw new RuntimeException(e);
        // }
        return "线程池: " + Thread.currentThread().getName() +
                "\tpaymentInfo_TimeOutHandler,id: " + id + ",耗时； " + timeNumber + " 秒";
    }

    // fallback兜底方案
    public String paymentInfo_TimeOutHandler(Integer id){
        return "8001提供者，线程池L " + Thread.currentThread().getName()
                + "\tpaymentInfo_TimeOutHandler系统繁忙，请稍后再试,id : " + id;
    }

    @GetMapping("/payment/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        String result = paymentService.paymentCircuitBreaker(id);
        log.info("******result：" + result);
        return result;
    }
}
